﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using InterpriseSuiteEcommerceCommon.DataAccess;
using InterpriseSuiteEcommerceCommon.Extensions;
using InterpriseSuiteEcommerceCommon.Tool;

namespace InterpriseSuiteEcommerceCommon.DTO
{
    public class GiftRegistry
    {
        private List<string> _errorMessage;

        public GiftRegistry() 
        {
            _errorMessage = new List<string>();
        }

        public GiftRegistry(int skinID, string locale) 
        {
            SkinID = skinID;
            LocaleSettings = locale;
            _errorMessage = new List<string>();
        }

        public int Counter { get; set; }
        public Guid RegistryID { get; set; }
        public Guid ContactGUID { get; set; }
        public DateTime? StartDate { get; set; }
        public DateTime? EndDate { get; set; }
        public string Title { get; set; }
        public string Message { get; set; }
        public string PictureFileName { get; set; }
        public Stream PictureStream { get; set; }
        public bool IsPrivate { get; set; }
        public string CustomURLPostfix { get; set; }
        public string WebsiteCode { get; set; }
        public string GuestPassword { get; set; }
        public DateTime? DateModified { get; set; }
        public string UserModified { get; set; }
        public DateTime? DateCreated { get; set; }
        public string UserCreated { get; set; }
        public bool IsActive { get; set; }
        public string OwnersFullName { get; set; }
        public IEnumerable<string> ListofErrorMessage { get { return _errorMessage.ToArray(); } }

        public IEnumerable<GiftRegistryItem> GiftRegistryItems 
        {
            get 
            {
                return GiftRegistryDA.GetGiftRegistryItemsByRegistryID(RegistryID);
            }
        }

        public int SkinID { get; set; }

        public void Validate()
        {
            _errorMessage = new List<string>();

            if (!StartDate.HasValue) 
            {
                _errorMessage.Add(AppLogic.GetString("editgiftregistry.error.1", SkinID, LocaleSettings)); 
            }

            if (!EndDate.HasValue)
            {
                _errorMessage.Add(AppLogic.GetString("editgiftregistry.error.2", SkinID, LocaleSettings));
            }

            if ((StartDate.HasValue && EndDate.HasValue) && (StartDate.Value > EndDate.Value))
            {
                _errorMessage.Add(AppLogic.GetString("editgiftregistry.error.7", SkinID, LocaleSettings));
            }

            if (Title.IsNullOrEmptyTrimmed())
            {
                _errorMessage.Add(AppLogic.GetString("editgiftregistry.error.3", SkinID, LocaleSettings));
            }

            if (CustomURLPostfix.IsNullOrEmptyTrimmed())
            {
                _errorMessage.Add(AppLogic.GetString("editgiftregistry.error.4", SkinID, LocaleSettings));
            }

            if (this.IsRegistryPrefixExist())
            {
                _errorMessage.Add(AppLogic.GetString("editgiftregistry.error.8", SkinID, LocaleSettings));
            }

            if (!Regex.IsMatch(CustomURLPostfix, DomainConstants.GIFTREGISTRY_CUSTOM_URL_REGEX_VALIDATION_VALUE))
            {
                _errorMessage.Add(AppLogic.GetString("editgiftregistry.error.9", SkinID, LocaleSettings));
            }

            //if (this.IsPhotoExceedToMaximumSize())
            //{
            //    long? maxRegistryPicture = AppLogic.AppConfig("GiftRegistry.MaxPhotoSize").TryParseLong();
            //    if (!maxRegistryPicture.HasValue) maxRegistryPicture = DomainConstants.DEFAULT_REGISTRY_PHOTOSIZE;
            //    _errorMessage.Add(string.Format("{0} {1} kb", AppLogic.GetString("editgiftregistry.error.10", SkinID, LocaleSettings), maxRegistryPicture));
            //}

        }

        private bool IsPhotoExceedToMaximumSize()
        {
            long? maxRegistryPicture = AppLogic.AppConfig("GiftRegistry.MaxPhotoSize").TryParseLong();
            if (!maxRegistryPicture.HasValue) maxRegistryPicture = DomainConstants.DEFAULT_REGISTRY_PHOTOSIZE;

            long size = ImageHelper.GetSize(PictureStream) / 1000;
            return size > maxRegistryPicture.Value;
        }

        public List<string> GetErrorMessage()
        {
            return _errorMessage; 
        }

        public bool HasErrors 
        {
            get 
            {
                return _errorMessage.Count > 0;
            }
        }

        public string LocaleSettings { get; set; }

        public bool IsEditMode { get; set; }

        public string ProcessPicture(string rootPath)
        {
            if (this.PictureStream.Length == 0) return this.PictureFileName;

            string configValue = string.Empty;
            string mime = "jpg";

            configValue = AppLogic.AppConfig("GiftRegistry.RegistryImageStyle");
            string[] imageSizeArr = configValue.Split(';')
                                        .Where(item => !item.IsNullOrEmptyTrimmed())
                                        .ToArray();

            if (imageSizeArr.Length > 1)
            {
                var hashTable = new Hashtable();
                imageSizeArr.ForEach(val => hashTable.Add(val.Split(':')[0], val.Split(':')[1]));
                mime = hashTable["mime"].ToString();
            }

            string giftRegistryPhotoPath = rootPath + "\\images\\giftregistry\\";
            try
            {
                var folderInfo = new DirectoryInfo(giftRegistryPhotoPath);
                if (!folderInfo.Exists) folderInfo.Create();
            }
            catch (IOException){}

            string correctFileExtension = ImageHelper.GetProperExtensions(this.PictureStream, mime);
            string fileName = this.RegistryID.ToString().ToLower() + correctFileExtension;
            string fullFileName = string.Format("{0}{1}", giftRegistryPhotoPath, fileName);

            long? maxRegistryPicture = AppLogic.AppConfig("GiftRegistry.MaxPhotoSize").TryParseLong();
            if (!maxRegistryPicture.HasValue) maxRegistryPicture = DomainConstants.DEFAULT_REGISTRY_PHOTOSIZE;

            ImageHelper.OptimizeAndSaveImage(PictureStream, fullFileName, maxRegistryPicture.Value);

            return fileName;
        }

        public string URLForViewing 
        {
            get 
            {
                return CurrentContext.FullyQualifiedApplicationPath() + "viewregistry.aspx?" + DomainConstants.GIFTREGISTRYPARAMCHAR + "=" + CustomURLPostfix;
            }
        }

        //property for paging
        public int RowNumber { get; set; }

        public static void DeleteRegistryImagesByIDs(IEnumerable<string> giftRegistryFileNames, string rootPath)
        {
            string giftRegistryPhotoPath = rootPath + "\\images\\giftregistry\\";
            try
            {
                giftRegistryFileNames.ForEach(pic =>
                {
                    string fullFileName = string.Format("{0}{1}", giftRegistryPhotoPath, pic);
                    if (File.Exists(fullFileName)) { File.Delete(fullFileName); }
                });
            }
            catch (IOException) { }
        }

    }
}
